package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketServer {

	public static int maxThread = Runtime.getRuntime().availableProcessors();
	
	private ExecutorService socketPools = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
	
	public void createNewWorker(Socket socket){
		if(maxThread > 0){
			maxThread--;
			ServerWorker worker = new ServerWorker();
			worker.setSocket(socket);
			socketPools.execute(worker);
		}else{
			try{
				BufferedWriter writer = new BufferedWriter(new PrintWriter(socket.getOutputStream()));
				writer.write("1");
				writer.flush();
				writer.close();
				socket.close();
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

/**
 * worker thread
 * @author liyuanliu
 *
 */
class ServerWorker implements Runnable {
	
	private Socket socket;
	
	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		String content = null;
		try{
			PrintWriter pWriter = new PrintWriter(socket.getOutputStream());
			BufferedReader bufReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			//BufferedWriter bufWriter = new BufferedWriter(new PrintWriter(socket.getOutputStream()));
		//	ByteBuffer buffer = ByteBuffer.allocate(8192);
			content = bufReader.readLine();
			while(!"Bye".equals(content)){
				//bufReader.read(buffer);
				System.out.println("Now server receive :"+content+" from client");
				pWriter.println("Server received Successfully");
				pWriter.flush();
				
				content = bufReader.readLine();
				System.out.println("Received:"+content);
				//buffer.flip();
				
//				bufWriter.write("Server received successfully!");
//				bufWriter.flush();
				
				//buffer.clear();
			}
			bufReader.close();
			//bufWriter.close();
			pWriter.close();
			SocketServer.maxThread++;
			socket.close();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
